package server;

import java.io.*;

/**
 * @author chengzhj
 * @data 2021/9/25 9:47 下午
 */
public class MyClassLoader extends ClassLoader {

    private String classPath;

    public MyClassLoader(String classPath) {
        this.classPath = classPath;
    }

    @Override
    protected Class<?> findClass(String name) throws ClassNotFoundException {
        // 字符替换
        String myFile = classPath + "/" + name.replace(".", "/") + ".class";

        Class clazz;
        byte[] bytes;

        try {
            // 获取.class文件的二进制字节
            InputStream in = new FileInputStream(myFile);
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024 * 4];
            int i = 0;
            while ((i = in.read(buffer)) != -1) {
                out.write(buffer, 0, i);
            }
            bytes = out.toByteArray();
            clazz = defineClass(name, bytes, 0, bytes.length);
            return clazz;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return super.findClass(name);
    }
}
